package com.sys.orders.head.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.sys.common.controller.BaseController;
import com.sys.common.pojo.ApiResponse;
import com.sys.common.pojo.ApiResponseEnum;
import com.sys.common.util.ConstatFinalUtil;
import com.sys.common.util.PageInfoUtil;
import com.sys.goods.pojo.AAddress;
import com.sys.goods.pojo.AAddressEnum;
import com.sys.goods.service.IGoodsDbService;
import com.sys.users.pojo.ACart;
import com.sys.users.pojo.ACartEnum;
import com.sys.users.pojo.AUsers;
import com.sys.users.pojo.AUsersEnum;
import com.sys.users.service.IUsersDbService;

/**
 * 用户首页操作
 * @author lby
 *
 */
@Controller
@RequestMapping(value = "/head/users",produces = "text/html;charset=UTF-8")
public class UsersHeadController extends BaseController
{
	@Autowired
	private IUsersDbService usersDbService;
	
	@Autowired
	private IGoodsDbService goodsDbService;
	
	
	/**
	 * 首页
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/main")
	public String main(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("===main======");
		/* 从session中获取信息 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		int usersId = users.getUsersId() ;
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("usersId", usersId);
		ApiResponse<AUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
		if(this.updateFlag == null || "".equalsIgnoreCase(this.updateFlag))
		{
			/* 清空信息 */
			apiResponse.clearInfo();
		}
		request.setAttribute("response", apiResponse.toJSON());
		/* 根据不同的判断,页面跳转 */
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			/* 修改页面 */
			return  "/head/users/usersUpdate" ; 
		}
		return "/head/users/main";
	}
	

	/**
	 * 更新
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/usersUpdateSubmit")
	public String usersUpdateSubmit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====usersUpdateSubmit=====");
		HttpSession session = request.getSession(); 
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 存储多个结果,Map存储 */
		Map<String, Object> dataMapJava = new HashMap<String, Object>();
		apiResponse.setDataMapJava(dataMapJava);
		
		/* 从session中获取信息 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		int usersId = users.getUsersId() ;
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		condMap.put("usersId", usersId);
		ApiResponse<AUsers> apiResponseRes = this.usersDbService.findOneUsersService(condMap);
		request.setAttribute("response", apiResponseRes.toJSON());
		
		users = apiResponseRes.getDataOneJava() ; 
		
		boolean updateFlag = false ; 
		/* 根据不同的判断,页面跳转 */
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			String phone = request.getParameter("userPhone");
			String sex = request.getParameter("userGender");
			
			users.setUserPhone(phone);
			users.setUserGender(sex);
			
			updateFlag = true ; 
		}
		
		/* 更新 */
		if(updateFlag)
		{
			apiResponse = this.usersDbService.updateOneUsersService(users);
			session.setAttribute("users", users);
		}
		apiResponse.setInfo(
				ConstatFinalUtil.INFO_JSON.getString(apiResponseRes.getCode() + ""),
				Collections.EMPTY_MAP);
		
		this.updateFlag = "true" ; 
		request.setAttribute("response", apiResponseRes.toJSON());
		return this.main(request, response);
	}
	
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response)
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====logout=====");
		/* 从session中移除数据 */
		HttpSession session = request.getSession() ;
		session.removeAttribute("users");
		return "redirect:/login" ; 
	}
	
	
	

	
	/**
	 * 购物车列表
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/cartList")
	public String cartList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		
		ConstatFinalUtil.SYS_LOGGER.info("============cartList==============");
		/* 准备路径 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		
		/* 分页信息 */
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 查询我的,查询启用的购物车 */
		condMap.put("userId", users.getUsersId());
		condMap.put("status", AUsersEnum.STATUS_ENABLE.getStatus());
		
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<ACart> apiResponse = this.usersDbService.findCondListCartService(null, condMap);
		/* 将结果存储到Request中 */
		request.setAttribute("response", apiResponse.toJSON());
		
		/* 页面跳转 */
		return "/head/users/cartList" ; 
	}
	
	/**
	 * 
	 */
	@RequestMapping("/cartInsert")
	public String cartInsert(HttpServletRequest request,HttpServletResponse response)
	{
		ConstatFinalUtil.SYS_LOGGER.info("======cartInsert==========");
		return "" ;
	}

	/**
	 * 购物车添加提交
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/cartInsertSubmit")
	@ResponseBody
	public String cartInsertSubmit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		
		ConstatFinalUtil.SYS_LOGGER.info("========cartInsertSubmit===============");
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 准备路径 */
		try
		{
			/* 需要返回json */
			String blindBoxId = request.getParameter("blindBoxId");
			String purchaseQuantity = request.getParameter("purchaseQuantity");
			
			/* 创建对象 */
			ACart cart = new ACart();
			
			/* 赋值 */
			cart.setUserId(users.getUsersId());
			cart.setBlindBoxId(Integer.valueOf(blindBoxId));
			cart.setPurchaseQuantity(Integer.valueOf(purchaseQuantity));
			cart.setStatus(ACartEnum.STATUS_ENABLE.getStatus());
			cart.setPubTime(new Date());
			
			/* 保存数据库 */
			apiResponse = this.usersDbService.saveOneCartService(cart);
			request.setAttribute("response", apiResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("添加购物车报错了;",e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		/* 成功,提示 */
		JSONObject resultJSON = apiResponse.toJSON();
		return resultJSON.toJSONString() ; 
	}

	/**
	 * 购物车更新提交
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/cartDelete")
	public String cartDelete(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
	{
		ConstatFinalUtil.SYS_LOGGER.info("======cartDelete=========");
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		/* 按照id查询 */
		String id = request.getParameter("id");
		condMap.put("cartDetailNumber", id);
		ApiResponse<ACart> apiResponse = this.usersDbService.findOneCartService(condMap);
		request.setAttribute("response", apiResponse.toJSON());
		
		ACart cart = apiResponse.getDataOneJava() ;
		/* 清空数量 */
		cart.setPurchaseQuantity(0);
		cart.setStatus(ACartEnum.STATUS_DISABLED.getStatus());
		
		ApiResponse<Object> apiResponseDb = this.usersDbService.updateOneCartService(cart);
		
		/* 成功,提示 */
		JSONObject resultJSON = apiResponseDb.toJSON();
		return this.cartList(request, response);
	}
	
	/*=====收货地址管理开始=====*/
	/**
	 * 收货地址列表页面
	 * @return
	 */
	@RequestMapping("/addressList")
	public String addressList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--addressList--");
		/* 只能查询自己的收货地址 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		
		condMap.put("userId", users.getUsersId());
		condMap.put("status", AAddressEnum.STATUS_ENABLE.getStatus());
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<AAddress> response = this.goodsDbService.findCondListAAddressService(pageInfoUtil, condMap);
		response.clearInfo();
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/head/users/addressList";
	}
	/**
	 * 打开添加收货地址页面
	 * @return
	 */
	@RequestMapping("/addressInsert")
	public String addressInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--addressInsert--");
		return "/head/users/addressInsert";
	}
	
	/**
	 * 添加收货地址提交操作
	 * @return
	 */
	@RequestMapping(value = "/addressInsertSubmit")
	public String addressInsertSubmit(String pubTimeStr , AAddress address,
			HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--addressInsertSubmit--");
		/* 保存结果 */
		ApiResponse dbResponse = new ApiResponse<Object>();
		
		/* 只能查询自己的收货地址 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		try
		{
			address.setUserId(users.getUsersId());
			/* 为对象赋值 */
			address.setPubTime(new Date());
			dbResponse = this.goodsDbService.saveOneAAddressService(address);
			ConstatFinalUtil.SYS_LOGGER.info("--收货地址添加返回结果:{}--",dbResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("添加一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		model.addAttribute("response", dbResponse.toJSON());
		return this.addressInsert();
	}
	
	/**
	 * 打开更新收货地址页面
	 * @return
	 */
	@RequestMapping("/addressUpdate")
	public String addressUpdate(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--addressUpdate--");
		String id = request.getParameter("id");
		String operType = request.getParameter("operType");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("addressId", id);
		/* 查询数据库 */
		ApiResponse<AAddress> response = this.goodsDbService.findOneAAddressService(condMap);
		AAddress address = response.getDataOneJava() ;
		response.clearInfo();
		/* 存储request */
		model.addAttribute("response", response.toJSON());
		
		if("update".equalsIgnoreCase(operType))
		{
			return "/head/users/addressUpdate";
		}
		return "/head/users/addressInfo";
	}
	
	/**
	 * 更新收货地址提交操作
	 * @return
	 */
	@RequestMapping(value = "/addressUpdateSubmit")
	public String addressUpdateSubmit(String id,MultipartFile file,
			HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--addressUpdateSubmit--");
		/* 返回关系 */
		ApiResponse dbResponse = new ApiResponse<Object>();
		/* 只能查询自己的收货地址 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		try
		{
			/* 准备查询条件 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("addressId", id);
			/* 查询数据库 */
			ApiResponse<AAddress> response = this.goodsDbService.findOneAAddressService(condMap);
			/* 获取java对象 */
			AAddress address = response.getDataOneJava() ;
			
			boolean flag = false ; 
			String operType = request.getParameter("operType");
			if("update".equalsIgnoreCase(operType))
			{
				/* 接收参数 */
				String consigneeName = request.getParameter("consigneeName");
				String consigneeNumber = request.getParameter("consigneeNumber");
				String addressInformation = request.getParameter("addressInformation");
				String isTheDefaultAddress = request.getParameter("isTheDefaultAddress");
				String postal = request.getParameter("postal");
				/* 设置属性 */
				address.setConsigneeName(consigneeName);
				address.setConsigneeNumber(consigneeNumber);
				address.setAddressInformation(addressInformation);
				address.setIsTheDefaultAddress(Byte.valueOf(isTheDefaultAddress));
				address.setPostal(postal);
				
				flag = true ; 
			}
			
			if(flag)
			{
				/* 数据库操作 */
				dbResponse = goodsDbService.updateOneAAddressService(address);
				ConstatFinalUtil.SYS_LOGGER.info("--收货地址添加返回结果:{}--",dbResponse.toJSON());
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("更新一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		model.addAttribute("response", dbResponse.toJSON());
		return "/head/users/addressUpdate";
	}
	
	/**
	 * 打开删除收货地址页面
	 * @return
	 */
	@RequestMapping("/addressDelete")
	public String addressDelete(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--addressDelete--");
		String id = request.getParameter("id");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("addressId", id);
		/* 查询数据库 */
		ApiResponse<AAddress> response = this.goodsDbService.findOneAAddressService(condMap);
		AAddress address = response.getDataOneJava() ;
		address.setStatus(AAddressEnum.STATUS_DISABLED.getStatus());
		ApiResponse<Object> apiResponse = this.goodsDbService.updateOneAAddressService(address);
		ConstatFinalUtil.SYS_LOGGER.info("结果:{}",apiResponse.toJSON().toJSONString());
		return "redirect:/head/users/addressList";
	}
	/*=====收货地址管理结束=====*/
}